import {BaseCrudApi} from "~/api/util/BaseService";
import {UnwrapNestedRefs} from "@vue/reactivity";
import {EditState} from "~/api/types";
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import {WeChatRole} from "~/api/wechat/role/types";

export class WeChatRoleApi extends BaseCrudApi<WeChatRole> {
    baseUrl: string = "/wechat/role";

    editOrgState: UnwrapNestedRefs<EditState<WeChatRole>> = reactive({
        visible: false,
        loading: false,
        title: "编辑数据权限",
        form: {},
    });

    editPermissionState: UnwrapNestedRefs<EditState<WeChatRole>> = reactive({
        visible: false,
        loading: false,
        title: "编辑接口权限",
        form: {},
    });

    onEditOrg(id?: string) {
        this.editOrgState.form = {};
        this.editOrgState.visible = true;
        if (id) {
            this.editOrgState.loading = true;
            this.load(id).then((res) => {
                this.editOrgState.form = res.data as any;
            }).catch((reason: any) => {
                console.log(reason);
            }).finally(() => {
                this.editOrgState.loading = false;
            });
        }
    }

    onEditPermission(id?: string) {
        this.editPermissionState.form = {};
        this.editPermissionState.visible = true;
        if (id) {
            this.editPermissionState.loading = true;
            this.load(id).then((res) => {
                this.editPermissionState.form = res.data as any;
            }).catch((reason: any) => {
                console.log(reason);
            }).finally(() => {
                this.editPermissionState.loading = false;
            });
        }
    }

    onCloseEditOrg() {
        this.editOrgState.visible = false;
        this.editOrgState.form = {};
    }

    onCloseEditPermission() {
        this.editPermissionState.visible = false;
        this.editPermissionState.form = {};
    }

    updateOrg(entity: WeChatRole) {
        return new Promise((resolve, reject) => {
            this.post("/updateOrg/" + entity.id, entity).then(res => {
                if (res) {
                    ElMessage.success(res.msg);
                    this.refreshTable();
                    this.afterSubmit();
                    resolve(res);
                } else {
                    this.afterSubmit();
                    reject(res);
                }
            });
        });
    }

    updatePermission(entity: WeChatRole) {
        return new Promise((resolve, reject) => {
            this.post("/updatePermission/" + entity.id, entity).then(res => {
                if (res) {
                    ElMessage.success(res.msg);
                    this.refreshTable();
                    this.afterSubmit();
                    resolve(res);
                } else {
                    this.afterSubmit();
                    reject(res);
                }
            });
        });
    }
}
